
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: Entity.java 377 2010-03-11 20:50:18Z archie.cobbs $
 */

package org.dellroad.sidekar;

import org.dellroad.sidekar.datastore.Datastore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class SchemaObject {

    final Logger log = LoggerFactory.getLogger(getClass());

    private final Database db;

    private Database.Opening opening;

    SchemaObject(Database db) {
        this.db = db;
        this.opening = this.db.getOpening();
    }

    /**
     * Get the database that this instance is associated with.
     */
    public final Database getDatabase() {
        return this.db;
    }
    
    // Convenience method
    final Datastore getDatastore() {
        return this.db.getDatastore();
    }

    /**
     * Check whether this instance is still valid. An instance is valid if it {@linkplain #getDatabase corresponds}
     * to an open {@link Database}. Once the associated {@link Database} is closed, this instance becomes invalid,
     * even if the associated {@link Database} is subsequently re-opened.
     *
     * @throws IllegalStateException if the associated {@link Database} is no longer open
     */
    public final void validate() {
        Database.Opening o = this.opening;
        if (o == null)
            throw new IllegalStateException("the associated Database is no longer open");
        o.validate();
    }

    // Invalidate this instance
    final synchronized void invalidate() {
        this.opening = null;
    }
}

